<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <!-- <el-form-item label="用户编号" prop="userNo">
        <el-input v-model="queryParams.userNo" placeholder="请输入用户编号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item> -->
      <el-form-item label="所属单位" prop="unit">
        <el-input v-model="queryParams.unit" placeholder="请输入所属单位" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入手机号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.isDisable" placeholder="用户状态" clearable style="width: 240px">
          <el-option v-for="dict in statusDictDatas" :key="parseInt(dict.value)" :label="dict.label" :value="!parseInt(dict.value)"/>
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['vote:user-info:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport"
                    v-hasPermi="['vote:user-info:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['vote:user-info:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="用户名" align="center" prop="userName" />
      <!-- <el-table-column label="用户昵称" align="center" prop="userNick" /> -->
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="用户编号" align="center" prop="userNo" />
      <el-table-column label="所属单位" align="center" prop="unit" />
      <el-table-column label="部门" align="center" prop="department" />
      <el-table-column label="部门简称" align="center" prop="shortDpm" />
      <el-table-column label="职位等级" align="center" prop="position" />
      <!-- <el-table-column label="用户等级" align="center" prop="userLevel" /> -->
      <el-table-column label="性别" align="center" prop="sex" />
      <!-- <el-table-column label="是否启用" align="center" prop="isDisable"> -->
        <!-- <template slot-scope="scope">
          <el-switch v-model="scope.row.isDisable" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->

      <el-table-column label="权重" align="center" prop="weight" />
      
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['vote:user-info:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['vote:user-info:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <!-- <el-form-item label="用户昵称" prop="userNick">
          <el-input v-model="form.userNick" placeholder="请输入用户昵称" />
        </el-form-item> -->
        <el-form-item label="用户编号" prop="userNo">
          <el-input v-model="form.userNo" placeholder="请输入用户编号" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="form.department" placeholder="请输入部门" />
        </el-form-item>
         <el-form-item label="部门简称" prop="shortDpm">
          <el-input v-model="form.shortDpm" placeholder="请输入部门简称" />
        </el-form-item>
        <el-form-item label="所属单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入所属单位" />
        </el-form-item>
        <el-form-item label="职位等级" prop="position">
          <el-input v-model="form.position" placeholder="请输入职位等级" />
        </el-form-item>
        <!-- <el-form-item label="用户等级" prop="userLevel">
          <el-input v-model="form.userLevel" placeholder="请输入用户等级" />
        </el-form-item> -->
        
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择">
                <el-option v-for="dict in sexDictDatas" :key="parseInt(dict.value)" :label="dict.label" :value="dict.label"/>
              </el-select>
        </el-form-item>
        <!-- <el-form-item label="是否启用" prop="isDisable">
            <el-switch v-model="form.isDisable" />
        </el-form-item> -->
        <el-form-item label="权重" prop="weight">
          <el-input-number v-model="form.weight" :min="1"  placeholder="请输入权重">0</el-input-number>
        </el-form-item>
       
        <el-form-item label="附件" prop="fileUrl">
          <!-- <el-input-number v-model="form.weight" :min="1"  placeholder="请输入权重">0</el-input-number> -->
          <fileUpload v-model="form.fileUrl" :limit="1"/>
        </el-form-item>

        <el-form-item label="用户简介">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>

        <!-- <el-form-item prop="propsVal" label="请选择">
          <el-radio-group v-model="form.propsVal" >
            <el-radio :label="1" border>同意</el-radio>
            <el-radio :label="2" border>拒绝</el-radio>
            <el-radio :label="3" border>弃权</el-radio>
          </el-radio-group>
        </el-form-item> -->


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 文件上传-->

    <!-- <el-dialog :title="uploadFile.title" :visible.sync="uploadFile.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept="*" :auto-upload="false" drag
                 :headers="uploadFile.headers" :action="uploadFile.url" :data="uploadFile.data" :disabled="uploadFile.isUploading"
                 :on-change="handleFileChange"
                 :on-progress="handleFileUploadProgress2"
                 :on-success="handleFileUploadSuccess">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或 <em>点击上传</em>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileUploadForm">确 定</el-button>
        <el-button @click="uploadFile.open = false">取 消</el-button>
      </div>
    </el-dialog> -->

    
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import { createUserInfo, updateUserInfo, deleteUserInfo, getUserInfo, getUserInfoPage, exportUserInfoExcel,changeUserStatue,importTemplate } from "@/api/vote/userInfo";
import {getBaseHeader} from "@/utils/request";
import {DICT_TYPE, getDictDatas} from "@/utils/dict";
import Editor from '@/components/Editor';
import FileUpload from "@/components/FileUpload";
export default {
  name: "UserInfo",
  components: {
    Editor,
    FileUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 投票用户信息列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        userName: null,
        userNick: null,
        userNo: null,
        unit: null,
        position: null,
        userLevel: null,
        mobile: null,
        sex: null,
        isDisable: null,
        remark: null,
        department: null,
        weight: null,
        shortDpm: null,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
      },
      //用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/vote/user-info/import'
      },
      sexDictDatas: getDictDatas(DICT_TYPE.SYSTEM_USER_SEX),
      statusDictDatas: getDictDatas(DICT_TYPE.COMMON_STATUS),
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getUserInfoPage(params).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        userName: undefined,
        userNick: undefined,
        userNo: undefined,
        unit: undefined,
        position: undefined,
        userLevel: undefined,
        mobile: undefined,
        sex: undefined,
        isDisable: true,
        remark: undefined,
        department: undefined,
        weight: 10,
        shortDpm: undefined,
        fileUrl: undefined,
        content: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加投票用户信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getUserInfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改投票用户信息";
      });
    },


    // 用户状态修改
    handleStatusChange(row) {
      changeUserStatue(row.id, row.isDisable).then(() => {
          this.$modal.msgSuccess(!row.isDisable?"禁用成功":"启用成功");
        }).catch(function() {
          row.isDisable = !row.isDisable;
        });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateUserInfo(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createUserInfo(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除投票用户信息编号为"' + id + '"的数据项?').then(function() {
          return deleteUserInfo(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
     /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.$download.excel(response, '用户导入模板.xls');
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 拼接提示语
      let data = response.data;
      let text = '创建成功数量：' + data.createUsernames.length;
      // for (const username of data.createUsernames) {
      //   text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      // }
      text += '<br />更新成功数量：' + data.updateUsernames.length;
      // for (const username of data.updateUsernames) {
      //   text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      // }
      text += '<br />更新失败数量：' + Object.keys(data.failureUsernames).length;
      for (const username in data.failureUsernames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username + '：' + data.failureUsernames[username];
      }
      this.$alert(text, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有投票用户信息数据项?').then(() => {
          this.exportLoading = true;
          return exportUserInfoExcel(params);
        }).then(response => {
          this.$download.excel(response, '投票用户信息.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },



  }
};
</script>
